var gulp = require('gulp'),
    walk    = require('walk'),
    del = require('del'),
    pngquant = require('imagemin-pngquant'),
    gulpLoadPlugins = require('gulp-load-plugins'),
    plugins = gulpLoadPlugins();
/*
* 说明：gulp-load-plugins模块，可以加载package.json文件中所有的gulp模块，这样新增的gulp模块不用声明
* */
var config = {
    src:'./src/',
    dist:"./dist/",
    copyFiles:[],
    /**
     * 雪碧图生成配置
     * @param prefix css前缀 ，也是图标所在目录，必填
     * @returns {*}
     * 生成less和png，分别存放于./src/less/ ./src/images/
     */
    spritesmithConfig : function (prefix, options) {
        var sprite_config = {
            imgName: prefix + '.png',
            cssName: prefix + '_sprite.less',
            cssFormat: 'less',
            cssSpritesheetName:prefix,
            cssOpts: {
                prefix: prefix,
                distpath:'../images/'  // css中生成图标的路径
            },
            cssTemplate: './less.template.handlebars',
            cssHandlebarsHelpers:{
                px2percent:function (sprite) {
                    var position_x = sprite.offset_x/(sprite.width - sprite.total_width)*100;
                    var position_y = sprite.offset_y/(sprite.height - sprite.total_height)*100;
                    return  (position_x===0?"0 ":position_x.toFixed(2) + "% ") + (position_y===0?"0":position_y.toFixed(2) + "%").replace(/\.00/g,"");
                }
            }
        };
        sprite_config = Object.assign({},sprite_config,options);
        return gulp.src( config.src + 'sprites/' + prefix + '/*' )
            .pipe( plugins.spritesmith( sprite_config ) )
            .pipe( plugins.if('*.png', gulp.dest(config.src + 'images/'), gulp.dest( config.src + 'less/' )) );
    }
};

/**
 * 雪碧图生成任务实例,该方法将会遍历sprite目录下的子目录，子目录名称为前缀。子目录必须由字母组成
 */
gulp.task('sprite', function () {
    var walker  = walk.walk( config.src + "sprites", { followLinks: false });
    walker.on("directories", function (root, dirStatsArray, next) {
        for( var i=0, len = dirStatsArray.length; i<len; i++ ){
            config.spritesmithConfig(dirStatsArray[i].name, { padding:10 })
        }
        next();
    });
});

gulp.task('render_less', function () {
    gulp.src(config.src + 'less/style.less')
        .pipe( plugins.less({ /*compress: true*/ }))
        .pipe( plugins.autoprefixer({
            browsers: ["> 0%"], // 主流浏览器的最新两个版本
            cascade: false // 是否美化属性值
        }))
        .pipe(gulp.dest(config.src + 'styles/'));
});

gulp.task('watch_less',['render_less'], function () {
    gulp.watch( [config.src + 'less/**/*.less'], ['render_less']);
});

// html
gulp.task('html', ['imagesmin','copy:otherfiles'], function() {

    return gulp.src( config.src + '*.html' ,{ base: config.src })
        .pipe( plugins.useref() )
        .pipe( plugins.if('*.html', plugins.htmlMinifier({collapseWhitespace: true}) ) )
        .pipe( plugins.if('*.js', plugins.uglify({ preserveComments:'some' }) ) )
        .pipe( gulp.dest( config.dist ) );
});

gulp.task('manifest-rename:pics', ['html'], function () {
    return gulp.src([ config.dist + 'pics.manifest.json', config.dist + '**/*.{js,css,html}'])
        .pipe( plugins.revCollector() )
        .pipe( plugins.if('*.js', plugins.rev()) )
        .pipe( plugins.if('*.css', plugins.rev()) )
        .pipe( gulp.dest( config.dist ) )
        .pipe( plugins.rev.manifest("jscss.manifest.json") )
        .pipe( gulp.dest( config.dist ) );
});

gulp.task('manifest-rename:jscss', ['manifest-rename:pics'],function () {
    return gulp.src([ config.dist + 'jscss.manifest.json', config.dist + '**/*.html'])
        .pipe( plugins.revCollector() )
        .pipe(gulp.dest( config.dist ));
});

// webserver
gulp.task('webserver', function() {
    gulp.src('./')
        .pipe( plugins.webserver({
            livereload: true,
            directoryListing: true
        }));
});

// images
gulp.task('imagesmin', function () {
    return gulp.src( config.src + 'images/*.{png,jpg,gif,svg}' ,{ base: config.src })
        .pipe( plugins.imagemin({
            optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            use: [ pngquant()]
        }))
        .pipe( plugins.rev())
        .pipe(gulp.dest( config.dist))
        .pipe( plugins.rev.manifest("pics.manifest.json"))
        .pipe(gulp.dest( config.dist));
});

gulp.task('clean:allfiles', function () {
    return del([config.dist + '**/*']);
});

gulp.task('clean:rev_manifest', ['manifest-rename:jscss'], function () {
    return del([config.dist + '/*.manifest.json']);
});

gulp.task('copy:otherfiles',function(){
    return gulp.src(config.copyFiles,{ base: config.src })
        .pipe(gulp.dest( config.dist ));
});

gulp.task('default', ['clean:allfiles'], function(){
    gulp.start('clean:rev_manifest');
});